import { createRouter, createWebHistory } from 'vue-router'

import ResourcesList from '@/views/ResourcesList.vue';
import Login from '@/views/Login.vue';
import Register from '@/views/Register.vue';
import Home from '@/views/Home.vue';
import ResourceDetail from '@/views/ResourceDetail.vue';
import Upload from '@/views/Upload.vue';
import ManageResources from '@/views/ManageResources.vue';

const routes = [

  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/resources',
    name: 'resources',  // 路由的名称
    component: ResourcesList  // 对应的组件
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/register',
    name: 'register',
    component: Register
  },
  {
    path: '/detail/:id',
    name: 'detail',
    component: ResourceDetail
  },
  {
    path: '/upload',
    name: 'upload',
    component: Upload
  },
  {
    path: '/manage',
    name: 'manage',
    component: ManageResources
  }
]

const router = createRouter({    //创建路由实例
  history: createWebHistory(),
  routes
})


// 路由守卫
router.beforeEach((to, from, next) => {
  const state = sessionStorage.getItem('first');

  if (!state && to.path !== '/') {
    // 如果没有 userInfo 并且访问的不是首页，则跳转到首页
    next('/');
  } else {
    // 否则正常跳转
    next();
  }
});


// 添加错误处理
router.onError((error) => {
  console.error('Router Error:', error)
})

export default router
